package producer;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * @author daxue0929
 * @date 2023/2/16
 */

public class PubSubProducer {
    public static void main(String[] args) throws IOException, TimeoutException {
        PubSubProducer pubSubProducer = new PubSubProducer();
        pubSubProducer.sengMessage();
    }

    private void sengMessage() throws IOException, TimeoutException {

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("101.42.26.40");
        factory.setPort(5672);
        factory.setVirtualHost("/itcast");
        factory.setUsername("admin");
        factory.setPassword("admin");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // 创建交换机、队列、绑定队列和交换机
        /**
         * exchangeDeclare(String exchange, BuiltinExchangeType type,
         *      boolean durable, boolean autoDelete, boolean internal, Map<String, Object> arguments)
         * exchange: 交换机的名称
         * type: 交换机类型
         *      BuiltinExchangeType:
         *          DIRECT("direct"), 定向
         *          FANOUT("fanout"), 扇形(广播), 就是发送消息到与此交换机绑定的所有队列
         *          TOPIC("topic"), 通配符的方式
         *          HEADERS("headers"); 参数匹配
         * durable: 是否持久化
         * autoDelete: 是否自动删除
         * internal: 内部使用一般设置为false
         * arguments: 参数列表，暂时设置为null
         */
        AMQP.Exchange.DeclareOk testFanout = channel.exchangeDeclare("test_fanout",
            BuiltinExchangeType.FANOUT, true, false, false, null);

        channel.queueDeclare("test_fanout_queue1", true, false, false, null);
        channel.queueDeclare("test_fanout_queue2", true, false, false, null);

        //队列交换机绑定
        channel.queueBind("test_fanout_queue1", "test_fanout", "");
        channel.queueBind("test_fanout_queue2", "test_fanout", "");

        //消息发送
        channel.basicPublish("test_fanout", "", null,
            "日志信息".getBytes(StandardCharsets.UTF_8));

        channel.close();
        connection.close();
    }
}
